import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { CascaderItem, DValidateRules, FormLayout } from 'ng-devui';
import { DeviceToolsService } from 'src/app/@core/services/device-tools/device-tools.service';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { MoldService } from 'src/app/@core/services/mold/mold.service';

@Component({
  selector: 'app-edit-moulds',
  templateUrl: './edit-moulds.component.html',
  styleUrls: ['./edit-moulds.component.scss']
})
export class EditMouldsComponent {
  msg:any;
  layoutDirection: FormLayout = FormLayout.Horizontal;
  options: any=[];
  status:any=['报废','在用'];
  chosenItem = '在用';
  option: Array<number> = [];//设备分类
  productionDate: Date
  assemblyTime: Date

  mould = {
    mouldNum: "",
    mouldName: "",
    mouldTypeId: null,
    model: "",
    positionId: null,
    purchaseDate: null,
    note: "",
    isEnabled: false
  }
  msgs: Array<Object> = [];
  message: Array<Object> = [];

  FixtureRules:{[key:string]:DValidateRules} = {
    fixtureNum: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*' },
        { minlength: 2, message: '*' },
        { maxlength: 40, message: '*编码长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*编码不能包含空格' }
      ],
    },
    fixtureName: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*名称不能为空' },
        { maxlength: 40, message: '*名称长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*名称不能包含空格' }
      ],
    },
    model: {
      messageShowType:'text',
      validators: [

      ],
    },
    fixtureTypeId: {
      messageShowType:'text',
      validators: [
        { required: true ,message: '*分类不能为空' },
      ],
    },
  }
  id: any;

  constructor(private ActivatedRoute:ActivatedRoute,private Router:Router,private DeviceToolsService:DeviceToolsService,private MoldService:MoldService){
  }
  ngOnInit(): void {
    this.ActivatedRoute.queryParams.subscribe(params => {
      const id = params.id;
      this.id = id;
      this.MoldService.GetMouldById(id).subscribe((res: any) => {
        this.mould = res;
        this.mould.purchaseDate = new Date(res.purchaseDate);
        this.chosenItem = this.mould.isEnabled ? '在用' : '报废';
      });
    })

   this.MoldService.GetMouldTypesWithChildren(1,999).subscribe((res: any) => {
    this.options = this.convertToCascaderItem(res.items);
    for(let node of res.items){
      const path = this.findClassByValue(node,this.mould.mouldTypeId)
      if(path){
        this.option = path
        break
      }
    }

    });
   this.mould.isEnabled=this.statusToBoolean(this.chosenItem);
  }
  convertToCascaderItem(data: any[]): CascaderItem[] {
    return data.map(item => {
      let cascaderItem: CascaderItem = {
        label: item.mouldTypeName,
        value: item.mouldTypeId,
      };
      if (item.subMouldTypes) {
        cascaderItem.children = this.convertToCascaderItem(item.subMouldTypes);
      }
      return cascaderItem;
    });
  }//转换数据格式为华为库练级菜单的数据格式
  CascaderonChanges($event:any){

    this.mould.mouldTypeId = $event[$event.length-1]
  }

  submit(){

    if(this.mould.mouldNum&&this.mould.mouldName&&this.mould.mouldTypeId){
      this.MoldService.UpdateMould(this.mould,this.id).subscribe((res: any) => {
        this.showToast('success','提示','更新成功');
        setTimeout(() => {
          this.Router.navigate(['/pages/mould/moulds'])
        }, 1500);
      },(error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
      }
      )

    }
  }

  cancle(){
    this.Router.navigate(['/pages/mould/moulds'])
  }

  showToast(type: any,summary:any,content:any) {
    switch (type) {
    default:
      this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  statusChange(){
    this.mould.isEnabled=this.statusToBoolean(this.chosenItem);
  }
  statusToBoolean(status: string): boolean {
    if (status === '在用') {
      return true;
    } else if (status === '报废') {
      return false;
    } else {
      throw new Error('Invalid status: ' + status);
    }
  }
  findClassByValue(node: any ,value:any,path=[]) {
    if(node.mouldTypeId === value){
      return[...path,node.mouldTypeId]
    }
    if(node.subMouldTypes){
      for(let subNode of node.subMouldTypes){
        const subPath = this.findClassByValue(subNode,value,[...path,node.mouldTypeId])
        if(subPath){
          return subPath
        }
      }
    }
  }
}
